package cn.car.service.impl;

import cn.car.domains.bo.QueryRoleBo;
import cn.car.domains.entity.SysRoleEntity;
import cn.car.exception.CarAccessControlException;
import cn.car.mapper.SysRoleMapper;
import cn.car.service.SysRoleService;
import jakarta.annotation.Resource;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SysRoleServiceImpl implements SysRoleService {


    @Resource
    private SysRoleMapper sysRoleMapper;

    @Override
    public Long addRole(SysRoleEntity role) {
        // 执行插入操作
        int rows;
        try {
            rows = sysRoleMapper.insertRole(role);
        } catch (DuplicateKeyException e) {
            throw CarAccessControlException.DATE_EXIST;
        }

        if (rows != 1) {
            throw CarAccessControlException.INSERT_ERROR.newInstance("插入角色失败");
        }
        return role.getId();
    }

    @Override
    public SysRoleEntity getRoleById(Long id) {
        return sysRoleMapper.selectById(id);
    }

    @Override
    public SysRoleEntity getRoleByCode(String roleCode) {
        return sysRoleMapper.selectByCode(roleCode);
    }

    @Override
    public void updateRole(SysRoleEntity role) {
        // 校验ID是否存在
        if (role.getId() == null) {
            throw CarAccessControlException.PARAMS_ERROR.newInstance("更新id不能为空");
        }

        // 执行更新操作
        int rows = sysRoleMapper.updateRole(role);

        if (rows != 1) {
            throw CarAccessControlException.DELETE_NOT_EXIST;
        }
    }

    @Override
    public void deleteRole(Long id) {
        // 校验ID是否存在
        if (id == null) {
            throw CarAccessControlException.PARAMS_ERROR.newInstance("删除id不能为空");
        }

        // 执行删除操作
        int rows = sysRoleMapper.deleteById(id);

        if (rows != 1) {
            throw CarAccessControlException.DELETE_NOT_EXIST;
        }
    }

    @Override
    public List<SysRoleEntity> list(QueryRoleBo query) {
        return sysRoleMapper.selectUserList(query);
    }
}
